package com.crm.dataReceive.controller;

import com.crm.custinfo.service.ICustInfoService;
import com.crm.dataReceive.domain.GetStart;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/starRatingFeedback")
public class StarRatingFeedbackController {
    public static final org.slf4j.Logger log = LoggerFactory.getLogger("starRatingFeedbackController");
    @Autowired
    private ISysConfigService baseSysConfigService;
    @Autowired
    private ICustInfoService custInfoService;
    @Anonymous
    @PostMapping("/tenant/{tenantId}")
    @ResponseBody
    public Map<String, Object> getStart(@RequestBody GetStart req) {
        try {
            String secretKey = baseSysConfigService.getItemValueByItemKey(req.getChannelSource());
            if (StringUtils.isBlank(secretKey)) {
                return result("500", "未找到对应渠道", null);
            }
            if (!req.getSecretKey().equals(secretKey)) {
                return result("500", "密钥错误", null);
            }
            if (req.getDays() > 7) {
                return result("500", "时间范围异常", null);
            }
            LocalDate currentDate = LocalDate.now();
            LocalDate targetDate = currentDate.minus(req.getDays(), ChronoUnit.DAYS);

            // 格式化日期为 yyyy-MM-dd
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String formattedDate = targetDate.format(formatter);
            Map<String, Object> inParams = new HashMap<String, Object>();
            inParams.put("start_time", formattedDate);
            inParams.put("channel_source", req.getChannelSource());
            List<Map<String, Object>> list = custInfoService.getStarStatusDetail2(inParams);
            return result("200", "获取成功", list);
        } catch (Exception e) {
           return result("500", "系统获取异常", null);
        }

    }
    private Map<String, Object> result(String code, String msg, List<Map<String, Object>> list) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("msg", msg);
        result.put("list", list);
        return result;
    }
}
